package de.uni.bremen.estudent.lbs.ui.phone;


import android.app.Dialog;
import android.app.FragmentManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import de.uni.bremen.estudent.lbs.R;
import de.uni.bremen.estudent.lbs.models.MyItemizedOverlay;
import de.uni.bremen.estudent.lbs.models.MyPosOverlay;
import de.uni.bremen.estudent.lbs.service.MensaUpdateService;
import de.uni.bremen.estudent.lbs.tasks.OverlayAsyncTask;
import de.uni.bremen.estudent.lbs.ui.widget.ActionBarHelper;
import de.uni.bremen.estudent.lbs.util.CategoryListAdapter;
import de.uni.bremen.estudent.lbs.util.CategoryListAdapter.ViewHolder;
import de.uni.bremen.estudent.lbs.util.Constants;
import de.uni.bremen.estudent.lbs.util.LocationAnalyzer;
import de.uni.bremen.estudent.lbs.util.LocationRequester;
import de.uni.bremen.estudent.lbs.util.UIUtil;
import de.uni.bremen.estudent.lbs.views.MyMapView;

import java.util.List;


/**
 * @author bahlfeld
 */
public final class HomeActivity extends MapActivity {

    static final int DIALOG_QRCODE_ID = 0;
    /**
     * Class tag.
     */
    private static final String TAG = "eStudentLBS - HomeActivity";

    /**
     * Instance of actionbarhelper.
     */
    private final ActionBarHelper mActionBarHelper = ActionBarHelper
                                    .createInstance(this);
    /**
     * List which contains the different overlays.
     */
    private List<Overlay> mapOverlays;

    private FragmentManager mFragmentManger;

    /**
     * Locations requester object.
     */
    private LocationRequester mLocationRequester;

    /**
     * The map controller.
     */
    private MapController mMapController;

    /**
     * Mapview which contains the map of google-maps.
     */
    private MyMapView mMapView;

    /**
     * Overlay which represents position of the user.
     */
    private MyPosOverlay mMyPosition;

    /**
     * qr code reader.
     */
    private String mQRCodeReader = null;

    /**
     * Returns an actionbarhelper instance.
     *
     * @return ActionbarHelper instance.
     */
    public ActionBarHelper getActionBarHelper() {
        return this.mActionBarHelper;
    }

    @Override
    public MenuInflater getMenuInflater() {
        return this.mActionBarHelper.getMenuInflater(super.getMenuInflater());
    }

    /**
     * Handler for the category items click event. Only for the category
     * fragment necessary.
     *
     * @param v View Object.
     */
    public void onCategoryListItemClick(final View v) {
        CategoryListAdapter.ViewHolder vh = (ViewHolder) v.getTag();
        if (vh != null) {
            SharedPreferences prefs = this.getSharedPreferences(Constants.PREFS_NAME,
                                                                0);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean(vh.categoryCheckBox.getText().toString(),
                              vh.categoryCheckBox.isChecked());
            editor.commit();
            new OverlayAsyncTask(this).execute();
        }

    }

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.startService(new Intent(this, MensaUpdateService.class));
        this.mActionBarHelper.onCreate(savedInstanceState);
        this.setContentView(R.layout.main);
        this.mMyPosition = new MyPosOverlay();

        // Support hack, methode is not available before honeycomb
        if (UIUtil.isIcsOrGreater()) {
            this.mFragmentManger = this.getFragmentManager();
            this.getActionBar().setHomeButtonEnabled(true);
        }
        // Handling for versions before honeycomb! Versions above should use
        // fragments...
        // zu naechste keine unterscheidung bezüglich der android version.

        // MapView setup...
        this.mMapView = (MyMapView) this.findViewById(R.id.mapview);
        this.mMapView.setBuiltInZoomControls(true);

        // Adding the overlays...
        this.mapOverlays = this.mMapView.getOverlays();
        this.mapOverlays.add(this.mMyPosition);

        // Setting up... map controller
        // Zoomstate to 16 and center map to the centre of the university.
        this.mMapController = this.mMapView.getController();
        this.mMapController.setZoom(Constants.ZOOM_LEVEL_16);
        this.mMapController.animateTo(Constants.GEO_POINT_OF_CAMPUS);
        this.mLocationRequester = new LocationRequester(this,
                                        new LocationListener() {

                                            @Override
                                            public void onLocationChanged(Location location) {
                                                // This event is important get
                                                // fired when location changed.
                                                // TODO : setting up the new
                                                // position in google maps...
                                                Log.d(TAG,
                                                      "Change own position to: "
                                                                                      + location.toString());
                                                if (HomeActivity.this.mMyPosition != null) {

                                                    GeoPoint currentLocation = new GeoPoint(
                                                                                    (int) (location.getLatitude() * Constants.GEO_POINT_UNIT),
                                                                                    (int) (location.getLongitude() * Constants.GEO_POINT_UNIT));
                                                    if (LocationAnalyzer.isGeoPointInCampus(currentLocation)) {
                                                        HomeActivity.this.mMyPosition.setLocation(location);
                                                        // HomeActivity.this.mMapController.animateTo(currentLocation);
                                                    } else {
                                                        HomeActivity.this.mMapController.animateTo(Constants.GEO_POINT_OF_CAMPUS);
                                                    }

                                                } else {
                                                    if (LocationAnalyzer.isGeoPointInCampus(location.getLatitude(),
                                                                                            location.getLongitude())) {
                                                        HomeActivity.this.mMyPosition = new MyPosOverlay();
                                                        HomeActivity.this.mMyPosition.setLocation(location);
                                                        HomeActivity.this.mMapView.getOverlays()
                                                                                        .add(HomeActivity.this.mMyPosition);
                                                    } else {
                                                        HomeActivity.this.mMapController.animateTo(Constants.GEO_POINT_OF_CAMPUS);
                                                    }

                                                }
                                            }

                                            @Override
                                            public void onProviderDisabled(String provider) {
                                                // TODO Nothing to do here
                                            }

                                            @Override
                                            public void onProviderEnabled(String provider) {
                                                // TODO Nothing to do here
                                            }

                                            @Override
                                            public void onStatusChanged(String provider,
                                                                        int status,
                                                                        Bundle extras) {
                                                // Nothing to do here.
                                            }
                                        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater menuInflater = this.getMenuInflater();
        menuInflater.inflate(R.menu.main, menu);

        // Calling super after populating the menu is necessary here to ensure
        // that the
        // action bar helpers have a chance to handle this event.
        return this.mActionBarHelper.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        int itemId = item.getItemId();
        switch (itemId) {
        case android.R.id.home:
            this.mMapController.setZoom(Constants.ZOOM_LEVEL_16);
            this.mMapController.setCenter(Constants.GEO_POINT_OF_CAMPUS);
            break;
        case R.id.menu_filter:
            this.getActionBarHelper().setRefreshActionItemState(true, itemId);
            this.startActivity(new Intent(this, FilterDialog.class));
            this.getActionBarHelper().setRefreshActionItemState(false, itemId);
            break;

        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPause() {
        if (this.mLocationRequester != null) {
            this.mLocationRequester.stop();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        if (this.mLocationRequester != null) {
            this.mLocationRequester.restart();
        }
        new OverlayAsyncTask(this).execute();
        super.onResume();
    }

    /**
     * Updates the overlays list of the mapview. If the overlay list is not
     * empty. List will be cleared.
     *
     * @param itemizedOverlay
     */
    public void updateOverlayItems(MyItemizedOverlay itemizedOverlay) {
        if (!this.mapOverlays.isEmpty()) {
            this.mapOverlays.clear();
        }
        this.mapOverlays.add(itemizedOverlay);
        // Add own position
        if (mMyPosition != null) {
            this.mapOverlays.add(mMyPosition);
        }
        // Say the mapview it should be redraw!
        this.mMapView.invalidate();
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }




    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        this.mActionBarHelper.onPostCreate(savedInstanceState);
    }

    @Override
    protected void onTitleChanged(CharSequence title, int color) {
        this.mActionBarHelper.onTitleChanged(title, color);
        super.onTitleChanged(title, color);
    }



}